package com.iceberg.adgt.domain;

import com.iceberg.adgt.common.DomainException;

import java.util.LinkedHashMap;
import java.util.Map;

final class Architecture {

	private final Map<String, Layer> layerMap = new LinkedHashMap<String, Layer>();
	private String name;
	private String author;

	Architecture() {
	}

	void addLayer(String name, int number) throws DomainException {
		if (!layerMap.containsKey(name)) {
			layerMap.put(name, new Layer(name, number));
		} else {
			throw new DomainException("Layer name already exists.");
		}
	}

	void addAllowedLayerToLayer(String fromLayer, String toLayer) throws DomainException {

		if (layerMap.containsKey(fromLayer)) {
			Layer fromLayerObject = layerMap.get(fromLayer);

			if (layerMap.containsKey(toLayer)) {
				Layer toLayerObject = layerMap.get(toLayer);
				fromLayerObject.addAllowedLayer(toLayerObject);
			} else {
				throw new DomainException("The layer that you want to add as a allowed layer doesn't exist!");
			}
		} else {
			throw new DomainException("Couldn't add a layer to a non-existant layer.");
		}
	}

	void removeAllowedLayerForLayer(String deleteLayer, String fromLayer) throws DomainException {
		if (layerMap.containsKey(fromLayer)) {
			Layer layer = layerMap.get(fromLayer);
			layer.removeAllowedLayer(deleteLayer);
		} else {
			throw new DomainException("The layer you want to delete from doesn't exist.");
		}
	}

	void addUnitToLayer(String unitName, String type, String layerName) throws DomainException {
		Layer layer = layerMap.get(layerName);
		if (layer != null) {
			layer.addUnit(new Unit(unitName, UnitType.valueOf(type)));
		}
	}

	void removeUnitFromLayer(String unitName, String unitType, String layerName) {
		Layer layer = layerMap.get(layerName);
		if (layer != null) {
			layer.removeUnitByUnitName(unitName, unitType);
		}
	}

	void removeLayer(String layerName) {
		if (layerMap.containsKey(layerName)) {
			layerMap.remove(layerName);
		}

	}

	Map<String, Layer> getLayerMap() {
		return layerMap;
	}

	String getName() {
		return name;
	}

	void setName(String name) throws DomainException {
		if (name.equals("")) {
			throw new DomainException("Name cannot be empty");
		} else {
			this.name = name;
		}
	}

	String getAuthor() {
		return author;
	}

	void setAuthor(String author) throws DomainException {
		if (author.equals("")) {
			throw new DomainException("Author cannot be empty");
		} else {
			this.author = author;
		}
	}
}
